import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cartItems: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  getters: {
    cartTotalPrice(state) {
      return state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
    }
  },
  mutations: {
    updateCartItemQuantity(state, { id, quantity }) {
      const item = state.cartItems.find(item => item.id === id);
      if (item) {
        item.quantity = quantity;
      }
    },
    removeFromCart(state, id) {
      state.cartItems = state.cartItems.filter(item => item.id !== id);
    }
  },
  actions: {
    updateCartItemQuantity({ commit }, payload) {
      commit('updateCartItemQuantity', payload);
    },
    removeFromCart({ commit }, id) {
      commit('removeFromCart', id);
    }
  }
});